package com.zsck.pos.net;


import androidx.annotation.NonNull;

import com.facebook.stetho.okhttp3.StethoInterceptor;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit封装
 */
public class RetrofitCilent {
    private static final String TAG = "RetrofitUtils";
    private static ApiService mApiService;
    /**
     * 单例模式
     */
    public static ApiService getApiService() {
        if (mApiService == null) {
            synchronized (RetrofitCilent.class) {
                if (mApiService == null) {
                    mApiService = new RetrofitCilent().getRetrofit();
                }
            }
        }
        return mApiService;
    }
    private RetrofitCilent(){}

    public ApiService getRetrofit() {
        // 初始化Retrofit
        ApiService apiUrl = initRetrofit(initOkHttp()).create(ApiService.class);
        return apiUrl;
    }

    /**
     * 初始化Retrofit
     */
    @NonNull
    private Retrofit initRetrofit(OkHttpClient client) {
        return new Retrofit.Builder()
                    .client(client)
                    .baseUrl(NetConfig.HOST)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
//                .addConverterFactory(LenientGsonConverterFactory.create(new GsonBuilder().disableHtmlEscaping().create()))
                .build();
    }

    /**
     * 初始化okhttp
     */
    @NonNull
    private OkHttpClient initOkHttp() {
        return new OkHttpClient().newBuilder()
                    .readTimeout(NetConfig.DEFAULT_TIME, TimeUnit.SECONDS)//设置读取超时时间
                    .connectTimeout(NetConfig.DEFAULT_TIME, TimeUnit.SECONDS)//设置请求超时时间
                    .writeTimeout(NetConfig.DEFAULT_TIME,TimeUnit.SECONDS)//设置写入超时时间
                    .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))//添加日志拦截器
                    .addInterceptor(getHeaderInterceptor())//添加请求头
                    .addNetworkInterceptor(new StethoInterceptor())
                    .retryOnConnectionFailure(true)//设置出现错误进行重新连接。
                    .build();
    }
    /**
     * 设置Header
     *
     * @return
     */
    private Interceptor getHeaderInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(@NonNull Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder();
                if(NetConfig.userInfo != null){
                    requestBuilder.addHeader("Authorization", NetConfig.userInfo.getAccessToken())
                            .addHeader("memberId", NetConfig.userInfo.getAccountId())
                            .addHeader("sourceType", "app");
                }
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        };

    }
}

